package com.syt.zdlb.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syt.entity.model.cmn.Dict;
import com.syt.entity.vo.cmn.DictEeVo;
import com.syt.zdlb.listEX.DictListener;
import com.syt.zdlb.mapper.DictMapper;
import com.syt.zdlb.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;// baseMapper 和 dictMapper 他们两个是一样的





    // 根据 dickCode 获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {

        // 根据 dictcode 获取对应的id
        Dict codeDict = this.getDictByDictCode(dictCode);
        // 获取子节点id
        if(null == codeDict) return null;
        return this.findChlidAll(codeDict.getId());


    }





// 根据 value 以及 根据dictcode 和 value 查询
    @Override
    public String getDictName(String dictCode, String value) {

        // 如果说 dictCode 为空，直接根据 value 查询
        if(StringUtils.isEmpty(dictCode)){
            // 直接根据 value 查询
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();// 查询条件
            queryWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            System.out.println("000000"+dict.getName());
            return dict.getName();
        }else {
            // 如果说 dictCode 不为空，直接根据 value和 dictcode 查询
             // 根据dictcode 查询dict 对象，得到 dict 值
//            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();// 查询条件
//            queryWrapper.eq("dict_code",dictCode);


            Dict codedict = this.getDictByDictCode(dictCode);
            Long parent_id = codedict.getId();
            // 根据dict_code和 value 进行查询
            Dict selectOne = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value));

            return selectOne.getName();
        }
    }



    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();// 查询条件
        queryWrapper.eq("dict_code",dictCode);
        Dict codedict = baseMapper.selectOne(queryWrapper);
        return codedict;
    }




    // 导入字典数据
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importBictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }




    // 实现 导出表格的方法
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8");
           // String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        // 查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
        for(Dict dict : dictList) {
            DictEeVo dictVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictVo, DictEeVo.class);
            dictVoList.add(dictVo);
        }
        // 调用方法进行写的操作
        EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
    } catch (IOException e) {
        e.printStackTrace();
    }

    }




    // 根据数据id 查询子数据列表
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChlidAll(Long id) {
        //根据数据id查询子数据列表
        // 引入 Qw实现查询
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();

        wrapper.eq("parent_id", id);

        List<Dict> dictlist = baseMapper.selectList(wrapper);// 封装

// 向 list 集合每个 dict 对象中设置 hasChildren
        for (Dict dict:dictlist) {

            Long dictId = dict.getId();

            boolean childernjiedian = this.isChildernjiedian(dictId);

            dict.setHasChildren(childernjiedian);

        }
        return dictlist;// 返回
    }



    // 判断 id 下面是否有节点
    private boolean isChildernjiedian(Long id) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();

        wrapper.eq("parent_id", id);


        Integer integer = baseMapper.selectCount(wrapper);

        // integer>0  1>0 有数据
        return integer > 0;
    }




















































/*

    //根据数据id查询子数据列表
    @Override
    public List<Dict> findChlidData(Long id) {

        //根据数据id查询子数据列表
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        // 0>0    1>0
        return count > 0;
    }

*/

}
